﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Project.MVC.Model;
namespace Project.MVC.MsSQLDAL
{
    public class ProductRepository : IProductRepository
    {
        LinqProjectDataContext dataContext;
        public ProductRepository()
        {
            dataContext = new LinqProjectDataContext();
        }

        public IQueryable<ProductInfo> GetList()
        {
            return dataContext.Products.Select(record => new ProductInfo
                {
                    Id = record.Id,
                    CategoryId=record.Id,
                    Title=record.Title,
                    Description=record.Description,
                    ImageList=General.GetList(record.Images)                    
                });
        }

        public bool Insert(ProductInfo value)
        {
            if (value == null)
                return false;
            try
            {
                var info = General.GetInfo(value);
                dataContext.Products.InsertOnSubmit(info);
                dataContext.SubmitChanges();
                value.Id = info.Id;
                return true;
            }
            catch (Exception)
            {
                throw;
            }
        }

        public bool Update(ProductInfo value)
        {
            if (value == null)
                return false;
            try
            {
                //var info = GetById(value.Id);
                var info = dataContext.Products.Where(c => c.Id == value.Id).SingleOrDefault();
                if (info != null)
                {
                    info.Title = value.Title;
                    return true;
                }
                return false;
            }
            catch (Exception)
            {
                throw;
            }
        }

        public bool Delete(ProductInfo value)
        {
            if (value == null)
                return false;
            try
            {
                //var info = GetById(value.Id);
                var info = dataContext.Products.Where(c => c.Id == value.Id).SingleOrDefault();
                if (info != null)
                {
                    dataContext.Products.DeleteOnSubmit(info);
                    return true;
                }

                return false;
            }
            catch (Exception)
            {
                throw;
            }
        }
        public int Count()
        {
            return dataContext.Products.Count();
        }

        public void Commit()
        {
            dataContext.SubmitChanges();
        }
    }
}
